class ParseSong
  attr_accessor :xlsx, :sheet, :title, :rows

  def initialize
    @xlsx = Roo::Spreadsheet.open(Rails.root.join("app/lib/song.xlsx").to_s
    )
    @sheet = xlsx.sheet(xlsx.sheets[0])
    @title = @sheet.row(1)
  end

  def singer_tags
    { 1 => "中国男星",
      "中国男星" => 1,
      2 => "中国女星",
      "中国女星" => 2,
      # 3 => "港台男星",
      # "港台男星" => 3,
      # 4 => "港台女星",
      # "港台女星" => 4,
      5 => "乐队组合",
      "乐队组合" => 5,
      6 => "欧美明星",
      "欧美明星" => 6,
      7 => "日韩明星",
      "日韩明星" => 7,
      8 => "童星",
      "童星" => 8,
      9 => "其他",
      "其他" => 9 }
  end

  def song_tags
    { 1 => "华语流行",
      "华语流行" => 1,
      2 => "日韩流行",
      "日韩流行" => 2,
      3 => "欧美流行",
      "欧美流行" => 3,
      4 => "广场舞",
      "广场舞" => 4,
      5 => "演唱会",
      "演唱会" => 5,
      6 => "儿歌童谣",
      "儿歌童谣" => 6,
      7 => "其他",
      "其他" => 7,
      8 => "民歌",
      "民歌" => 8,
    }
  end

  # 导入之前要把 id_seq 还原
  def import
    @sheet.each(name: '视频内容', content_id: '媒资地址', uuid: '视频文件名', pinyin: '歌曲搜索关键字', time_duration: '时长', language: '语种', mv_type: '类型', redundant_song_tag_name: '风格流派', redundant_singer_name: '歌手', redundant_singer_tag_name: '歌手类别', redundant_singer_pinyin: '歌手搜索关键字') do |row|
      next if row[:uuid] == '视频文件名'
      next if Song.find_by_uuid(row[:uuid])

      begin
        puts row[:name]

        song = Song.new(name: row[:name], content_id: row[:content_id], uuid: row[:uuid], pinyin: row[:pinyin], time_duration: row[:time_duration], language: row[:language], mv_type: row[:mv_type], redundant_song_tag_name: row[:redundant_song_tag_name], redundant_singer_name: row[:redundant_singer_name], redundant_singer_tag_name: row[:redundant_singer_tag_name], redundant_singer_pinyin: row[:redundant_singer_pinyin])

        # 歌曲类型
        song.song_tag_id = song_tags[row[:redundant_song_tag_name]]

        # 创建歌手
        singer_names = row[:redundant_singer_name].gsub("、", "/").split("/")
        singer_names.each_with_index do |singer_name, singer_name_index|
          singer = Singer.find_or_create_by(name: singer_name)

          unless singer.id
            singer.pinyin = row[:redundant_singer_pinyin].gsub(" ", "/").split("/")[singer_name_index]
            singer.singer_tag_id = singer_tags[row[:redundant_singer_tag_name].gsub(" ", "/").split("/")[singer_name_index]]
            singer.save
          end

          song.singers << singer
        end

        song.save
      rescue Exception => ex
        binding.pry
      end
    end
  end
end
